package com.bootdo.zk.service;

import com.bootdo.zk.IZKService;
import org.apache.log4j.Logger;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;


public class ZKService implements IZKService {

    Logger logger = Logger.getLogger(ZKService.class);

    private ZooKeeper zk;

    private static final String PARENT_PATH = "/FANGKUN_ZK";

    Watcher startWatcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            System.out.println(event);
            switch (event.getState()) {
                case SyncConnected:
                    break;
                case Disconnected:
                    break;
                case Expired:
                    break;
                case Closed:
                    break;
            }
        }
    };

    public ZKService(String hostPort, int timeout) {
        try {
            zk = new ZooKeeper(hostPort, timeout, startWatcher);
            registry();
        } catch (IOException e) {
//           logger.error("ZKService init error" , e);
        }
    }

    @Override
    public void registry() {
        try {
            final Stat exists = zk.exists(PARENT_PATH, startWatcher);
            if (exists == null) {
                String result = zk.create(PARENT_PATH, PARENT_PATH.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
                System.out.println(result);
            }
        } catch (KeeperException | InterruptedException e) {
//            logger.error("registry error" , e);
        }
    }

    @Override
    public String createNode(String path, byte[] data, CreateMode createMode)  {
        try {
            final Stat exists = zk.exists(path, false);
            if (exists == null)
            {
                return  zk.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, createMode);
            }
            return path;
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }

}
